﻿using System.Windows.Forms;
using System;
using System.Data;
using Npgsql;
using NpgsqlTypes;
using System.IO;
using System.ComponentModel;

namespace DbWriter
{
    public partial class frmDbwriter : Form
    {
        bool endian;
        // исходный массив
        //заголовок
        ushort[] head = new ushort[10];
        byte[] b = new byte[223060];
        // переменные для заголовка
        DateTime mDateTime;
        ushort seans, nr1, nr0;
        // мощность сигнала
        uint[] m680 = new uint[680];
        uint[,] akf = new uint[170, 18];
        uint[] adc = new uint[680];
        ushort[] serv = new ushort[180];
        // v format
        uint[,] dat1 = new uint[230, 10];
        uint[,] dat2 = new uint[230, 10];
        uint[] apower = new uint[230];
        uint[] nadc1 = new uint[230];
        uint[] nadc2 = new uint[230];
        uint[] vserv = new uint[230];

        // s new format
        uint[,] akf1 = new uint[680, 19];
        uint[,] akf2 = new uint[680, 19];
        uint[,] akf3 = new uint[680, 19];
        uint[,] akf4 = new uint[680, 19];
        uint[] ipower1 = new uint[680];
        uint[] ipower2 = new uint[680];
        uint[] nsadc1 = new uint[680];
        uint[] nsadc2 = new uint[680];
        uint[] nsadc3 = new uint[680];
        uint[] nsadc4 = new uint[680];
        DataSet myDS = new DataSet();
        DataTable dt,dp,dta1,dta2,dd1,dd2;
        NpgsqlConnection conn;
        NpgsqlCommand command_v_power, command_v_adc1, command_v_adc2, command_v_dat1,command_v_dat2, commandh;
        string sql_v_power,sql_v_adc1,sql_v_adc2,sql_v_dat1,sql_v_dat2, command_h;
        FileStream writeStream;
        BinaryWriter writeBinary;
        public frmDbwriter()
        {
            InitializeComponent();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            bool endian = BitConverter.IsLittleEndian;
            byte [] b = new byte[4];
            conn = new NpgsqlConnection("Server=217.12.215.17;Port=5432;User Id=ax;Password=658706;Database=ions2;");
            conn.Open();
            //--header---
            commandh = new NpgsqlCommand(command_h, conn);
            commandh.Parameters.Add(new NpgsqlParameter("p_type", NpgsqlDbType.Integer));
            commandh.Parameters.Add(new NpgsqlParameter("p_id", NpgsqlDbType.Bigint));
            commandh.Parameters["p_type"].Value = 2; //v тип
            commandh.Parameters["p_id"].Value = long.Parse(tbId.Text.Trim());
            //--power---
            command_v_power = new NpgsqlCommand(sql_v_power, conn);
            command_v_power.Parameters.Add(new NpgsqlParameter("p_hid ", NpgsqlDbType.Bigint));
            command_v_power.Parameters["p_hid"].Value = long.Parse(tbId.Text.Trim());
            //--adc1---
            command_v_adc1 = new NpgsqlCommand(sql_v_adc1, conn);
            command_v_adc1.Parameters.Add(new NpgsqlParameter("p_hid ", NpgsqlDbType.Bigint));
            command_v_adc1.Parameters["p_hid"].Value = long.Parse(tbId.Text.Trim());
            //--adc2---
            command_v_adc2 = new NpgsqlCommand(sql_v_adc2, conn);
            command_v_adc2.Parameters.Add(new NpgsqlParameter("p_hid ", NpgsqlDbType.Bigint));
            command_v_adc2.Parameters["p_hid"].Value = long.Parse(tbId.Text.Trim());
            //--dat1---
            command_v_dat1 = new NpgsqlCommand(sql_v_dat1, conn);
            command_v_dat1.Parameters.Add(new NpgsqlParameter("p_hid ", NpgsqlDbType.Bigint));
            command_v_dat1.Parameters["p_hid"].Value = long.Parse(tbId.Text.Trim());
            //--dat2---
            command_v_dat2 = new NpgsqlCommand(sql_v_dat2, conn);
            command_v_dat2.Parameters.Add(new NpgsqlParameter("p_hid ", NpgsqlDbType.Bigint));
            command_v_dat2.Parameters["p_hid"].Value = long.Parse(tbId.Text.Trim());
           /*/ NpgsqlParameter Colum1 = new NpgsqlParameter("pmeasure_date", NpgsqlDbType.Date);
            Colum1.Direction = ParameterDirection.Output;
            Colum1.SourceColumn = "measure_date";
            //Colum1.Size = 8;
            commandh.Parameters.Add(Colum1);
            NpgsqlParameter Colum2 = new NpgsqlParameter("pseans", NpgsqlDbType.Smallint);
            Colum2.Direction = ParameterDirection.Output;
            Colum2.SourceColumn = "seans";
            //Colum2.Size = 2;
            commandh.Parameters.Add(Colum2);
            NpgsqlParameter Colum3 = new NpgsqlParameter("pnr1", NpgsqlDbType.Integer);
            Colum3.Direction = ParameterDirection.Output;
            Colum3.SourceColumn = "nr1";
           // Colum3.Size = 4;
            commandh.Parameters.Add(Colum3);
            NpgsqlParameter Colum4 = new NpgsqlParameter("pnr2", NpgsqlDbType.Integer);
            Colum4.SourceColumn = "nr2";
            //Colum4.Size = 4;
            Colum4.Direction = ParameterDirection.Output;
            commandh.Parameters.Add(Colum4);/*/
            try
            {
                NpgsqlDataAdapter da = new NpgsqlDataAdapter(commandh);
                NpgsqlDataAdapter da_p = new NpgsqlDataAdapter(command_v_power);
                NpgsqlDataAdapter da_adc1 = new NpgsqlDataAdapter(command_v_adc1);
                NpgsqlDataAdapter da_adc2 = new NpgsqlDataAdapter(command_v_adc2);
                NpgsqlDataAdapter da_dat1 = new NpgsqlDataAdapter(command_v_dat1);
                NpgsqlDataAdapter da_dat2 = new NpgsqlDataAdapter(command_v_dat2);
                da.Fill(myDS,"header");
                da_p.Fill(myDS,"power");
                da_adc1.Fill(myDS,"adc1");
                da_adc2.Fill(myDS,"adc2");
                da_dat1.Fill(myDS,"dat1");
                da_dat2.Fill(myDS,"dat2");
                dt = myDS.Tables["header"];
                dp = myDS.Tables["power"];
                dta1 = myDS.Tables["adc1"];
                dta2 = myDS.Tables["adc2"];
                dd1 = myDS.Tables["dat1"];
                dd2 = myDS.Tables["dat2"];
                foreach (DataRow row in dd1.Rows)
                {
                    long[] ts = (long[])row[0];
                    foreach (long item in ts)
                    {
                       // MessageBox.Show(item.ToString());
                    }
                }
                //MessageBox.Show(dd1.Rows[0][0].GetType().ToString());
                /*/commandh.ExecuteNonQuery();
                DateTime hdate = (DateTime)Colum1.Value;
                int hseans = (short)Colum2.Value;
                int hnr1 = (int)Colum3.Value;
                int hnr2 = (int)Colum4.Value;/*/

            }
            catch (NpgsqlException nex)
            {
               MessageBox.Show(nex.Message);
               MessageBox.Show(nex.InnerException.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
                conn = null;
            }
            
            try
            {
                mDateTime = (DateTime)dt.Rows[0]["measure_date"];
                head[0] = (ushort)mDateTime.Day;
                head[1] = (ushort)mDateTime.Month;
                head[2] = (ushort)mDateTime.Year;
                head[3] = (ushort)mDateTime.Hour;
                head[4] = (ushort)mDateTime.Minute;
                head[5] = (ushort)mDateTime.Second;
                head[6] = ushort.Parse(dt.Rows[0]["seans"].ToString());
                head[7] = ushort.Parse(dt.Rows[0]["nr1"].ToString());
                head[8] = ushort.Parse(dt.Rows[0]["nr2"].ToString());
                writeStream = new FileStream("c:\\vfile222.dat", FileMode.Create);
                MemoryStream mstream = new MemoryStream();
                writeBinary = new BinaryWriter(writeStream);
                // write header
                foreach (ushort i in head)
                {
                    writeBinary.Write(i);
                    mstream.Write(
                }
                //writeBinary.Close();
               // writeStream = new FileStream("c:\\vfile222.dat", FileMode.Append);
               // writeBinary = new BinaryWriter(writeStream);
                // write dat
                for (int i = 0; i < 230; i++ )
                {
                    long[] ts1 = (long[])dd1.Rows[i][0];
                    long[] ts2 = (long[])dd2.Rows[i][0];
                    long pw = (long)dp.Rows[i][0];
                    writeBinary.Write(unchecked((uint)ts1[0]));
                    writeBinary.Write(unchecked((uint)ts2[0]));
                    writeBinary.Write(unchecked((uint)pw));
                    for (int j = 1; j < 10; j++)
                    {
                        writeBinary.Write(unchecked((uint)ts1[j]));
                        writeBinary.Write(unchecked((uint)ts2[j]));
                    }

                }
               // writeBinary.Close();
                //writeStream = new FileStream("c:\\vfile222.dat", FileMode.Append);
               // writeBinary = new BinaryWriter(writeStream);
                //write acp
                for (int i = 0; i < 230; i++)
                {
                    long acp1 = (long)dta1.Rows[i][0];
                    long acp2 = (long)dta2.Rows[i][0];
                    writeBinary.Write(unchecked((uint)acp1));
                    writeBinary.Write(unchecked((uint)acp2));
                }
               // writeBinary.Close();
                //writeStream = new FileStream("c:\\vfile222.dat", FileMode.Append);
               // writeBinary = new BinaryWriter(writeStream);
                //write unused
                for (int i = 0; i < 820; i++)
                {
                    byte zr = 0;
                    writeBinary.Write(zr);
                }
               // writeBinary.Close();
               // writeStream = new FileStream("c:\\vfile222.dat", FileMode.Append);
               // writeBinary = new BinaryWriter(writeStream);
                //write label
                for (int i = 0; i < 230; i++)
                {
                    short lb = 0;
                    writeBinary.Write(lb);
                }
                writeBinary.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void frmDbwriter_Load(object sender, EventArgs e)
        {
            command_h = "SELECT measure_date, seans, nr1, nr2 FROM headerall WHERE measure_type = :p_type AND id = :p_id";
            sql_v_power = "SELECT nadc as power FROM nulladc WHERE header_id = :p_hid AND canal = 0 AND dtype = 1";
            sql_v_adc1 = "SELECT nadc as adc1 FROM nulladc WHERE header_id = :p_hid AND canal =1 AND dtype = 0";
            sql_v_adc2 = "SELECT nadc as adc2 FROM nulladc WHERE header_id = :p_hid AND canal =2 AND dtype = 0";
            sql_v_dat1 = "SELECT string_to_array(array_to_string(akf,','),',')::bigint[] as dat1 FROM data_v WHERE header_id = :p_hid AND data_type = 1";
            sql_v_dat2 = "SELECT string_to_array(array_to_string(akf,','),',')::bigint[] as dat2 FROM data_v WHERE header_id = :p_hid AND data_type = 2";
            
        }
    }
}
